package com.ruoyi.cyinfo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.cyinfo.domain.InfoCarryMoney;
import com.ruoyi.cyinfo.domain.InfoCheckin;
import com.ruoyi.cyinfo.domain.InfoUserOther;
import com.ruoyi.cyinfo.mapper.InfoCarryMoneyMapper;
import com.ruoyi.cyinfo.mapper.InfoCheckinMapper;
import com.ruoyi.cyinfo.mapper.InfoUserOtherMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/wechat")
public class WeChatLoginController extends BaseController {

    private static final String APPID = "wx4b6ff4e06aa0690e";
    private static final String SECRET = "d0d5b8484674156fc3000e4bc6a4c3b9";

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private InfoUserOtherMapper userOtherMapper;

    @Autowired
    private InfoCheckinMapper checkinMapper;

    @Autowired
    private InfoCarryMoneyMapper carryMoneyMapper;

    @PostMapping("/login")
    public AjaxResult login(@RequestParam SysUser weChatUser){
        //登录接口api
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        //设置登录接口参数
        String params = "appid="+APPID+"&secret="+SECRET+"&js_code="+weChatUser.getJsCode()+"&grant_type=authorization_code";
        //掉用api
        String s = HttpUtils.sendGet(url, params);
        //取openid
        JSONObject jsonObject = JSON.parseObject(s);
        Object openid = jsonObject.get("openid");
        weChatUser.setOpenId(String.valueOf(openid));
        SysUser user = sysUserMapper.selectUserByOpenId(String.valueOf(openid));
        if (StringUtils.isNull(user)){
            //新增
            sysUserMapper.insertUser(weChatUser);
            SysUser user1 = sysUserMapper.selectUserByOpenId(String.valueOf(openid));
            //存其他信息表
            InfoUserOther userOther = new InfoUserOther();
            userOther.setSysUserId(user1.getUserId());
            InfoCarryMoney infoCarryMoney = new InfoCarryMoney();
            infoCarryMoney.setSysUserId(user1.getUserId());
            InfoCheckin infoCheckin = new InfoCheckin();
            infoCheckin.setSysUserId(user1.getUserId());
            userOtherMapper.insertInfoUserOther(userOther);
            checkinMapper.insertInfoCheckin(infoCheckin);
            carryMoneyMapper.insertInfoCarryMoney(infoCarryMoney);
        }
        return AjaxResult.success(weChatUser);
    }
}
